<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://doc.hyperf.io
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Exception\Handler;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Psr\Http\Message\ResponseInterface;
use App\Utils\ServerUtil;
use Throwable;
use App\Utils\ApiUtils;
use App\Exception\BusinessException;

class BusinessExceptionHandler extends ExceptionHandler
{
    /**
     * @var StdoutLoggerInterface
     */
    protected $logger;

    public function __construct(StdoutLoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    public function handle(Throwable $throwable, ResponseInterface $response)
    {

        if ($throwable instanceof BusinessException) {
            $this->stopPropagation();
            $data = json_encode(ApiUtils::send($throwable->getCode(), $throwable->getMessage()), JSON_UNESCAPED_UNICODE);
            ServerUtil::info('业务异常捕获错误日志', ['msg' => $throwable->getMessage(), 'line' => $throwable->getLine(), 'file' => $throwable->getFile(), 'strace' => $throwable->getTraceAsString()]);
            return $response->withStatus(200)->withBody(new SwooleStream($data));
        }
        return $response;
    }

    public function isValid(Throwable $throwable): bool
    {
        return true;
    }
}
